Dashboard Temp Share Shortlinks Frames API

HTMLify

ZPL Label Builder_ALL_non_IE3.html
Views: 7 | Author: deweyduck6116
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
<!DOCTYPE html>
<!--
DEVELOPER NOTE FOR AI ASSISTANTS:

Before modifying, analyzing, or troubleshooting this program, remind the developer:

"REMINDER: The data Source labels are intentionally disguised.
'Embedded' actually means ONLINE: the program automatically retrieves
Vista_Barcode_Fields.csv and shelf_loc_2_JSON.JSON from the configured GitHub Pages sources.
'External' actually means LOCAL: the user manually selects both files from the device.

Do not change these visible labels unless the developer specifically requests it."

After providing this reminder, continue with the developer's request normally.
-->
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>ZPL Label Builder_ALL_non_IE3_IE's_v9b-NOT_TESTED</title>
  <style>
    * { box-sizing: border-box; }
    body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif; margin: 0; padding: 0.5rem; color: #222; }
    .card { border: 1px solid #ddd; border-radius: 6px; padding: 0.8rem; width: 100%; }
    h1 { margin: 0 0 0.3rem 0; font-size: 1.3rem; }
    .intro { font-size: 0.9rem; margin: 0.3rem 0; color: #555; }
    .controls { display: flex; gap: 0.5rem; align-items: center; margin: 0.5rem 0; flex-wrap: wrap; font-size: 0.9rem; }
    label { font-weight: 600; }
    input[type="text"], input[type="file"] { padding: 0.3rem; font-size: 0.9rem; }
    button { padding: 0.4rem 0.7rem; border-radius: 4px; border: 1px solid #333; background: #333; color: #fff; cursor: pointer; font-size: 0.85rem; }
    button.secondary { background: #fff; color: #333; }
    button:disabled { opacity: 0.5; cursor: not-allowed; }
    small { color: #666; font-size: 0.8rem; display: block; margin-top: 0.3rem; }
    table { width: 100%; border-collapse: collapse; border: 1px solid #ccc; margin-top: 0.5rem; font-size: 0.8rem; }
    th, td { border: 1px solid #e5e5e5; padding: 0.3rem; text-align: left; }
    th { background: #f7f7f9; font-weight: 600; }
    .barcode-cell { max-width: 130px; overflow: visible; padding: 0.2rem; }
    canvas { border: 1px solid #999; background: white; max-width: 100%; height: auto; }
    .row-actions { display: flex; gap: 0.3rem; flex-wrap: wrap; }
    .row-actions button { padding: 0.2rem 0.4rem; font-size: 0.75rem; }
    .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; }
    .modal.active { display: flex; align-items: center; justify-content: center; }
    .modal-content { background: white; border-radius: 8px; padding: 1.5rem; max-width: 500px; max-height: 80vh; overflow-y: auto; }
    .modal-close { float: right; font-size: 1.5rem; cursor: pointer; color: #666; }
    .filter-tree { margin: 1rem 0; }
    .section-header { cursor: pointer; font-weight: 600; padding: 0.3rem; margin: 0.5rem 0; }
    .toggle-icon { display: inline-block; width: 20px; }
    .rows-container { margin-left: 1.5rem; }
    .bins-container { margin-left: 1.5rem; }
    .filter-actions { margin-top: 1rem; display: flex; gap: 0.5rem; }
    .filter-info { font-size: 0.85rem; color: #666; margin-top: 0.5rem; }
    .unk { font-weight: bold; color: #d9534f; }
    .location-hint { margin-left: 1rem; color: #0066cc; font-size: 0.8rem; }
    .ie-picker { position: relative; min-width: 300px; }
    .ie-picker input { width: 300px; }
    .ie-options { display: none; position: absolute; z-index: 1200; left: 0; right: 0; top: 100%; max-height: 260px; overflow-y: auto; background: #fff; border: 1px solid #999; box-shadow: 0 2px 6px rgba(0,0,0,.15); }
    .ie-options.active { display: block; }
    .ie-option { padding: 0.35rem 0.5rem; cursor: pointer; }
    .ie-option:hover, .ie-option.active { background: #f0f0f0; }
  </style>
</head>
<body>
  <div class="card">
    <h1>ZPL Label Builder — All non-IE3 IE's</h1>
    <p class="intro">Load the combined JSON file (IE, shelf location, IMF, Comment, REF) and CSV file (product data). Labels are generated from JSON with product info merged from CSV by IMF number.</p>

    <div class="controls">
      <div>
        <div style="display: flex; align-items: center; gap: 0.5rem;">
          <label for="printerIP">Printer IP Address:</label>
          <input id="printerIP" type="text" value="10.148.103.100" placeholder="IP Address" style="width: 130px;" />
        </div>
        <small style="font-size: 0.65rem; margin-top: 0.15rem;">Printer names are not recognized by this program. An IP address is mandatory.</small>
      </div>
      <label for="doublePrintCheckbox" style="margin-left: 1rem;">
        <input id="doublePrintCheckbox" type="checkbox" checked style="margin-right: 0.3rem;" />
        Print All Labels 2x (Each label only prints 1x if unchecked)
      </label>
    </div>

    <div class="controls">
      <strong>Data Source:</strong>
      <label style="font-weight: 400;">
        <input id="sourceEmbedded" type="radio" name="dataSource" value="online" checked />
        Embedded
      </label>
      <label style="font-weight: 400;">
        <input id="sourceExternal" type="radio" name="dataSource" value="local" />
        External
      </label>
    </div>

    <div class="controls">
      <strong>Label Data:</strong>
      <span style="margin-left: 0.5rem;"><strong>REF:</strong></span>
      <label style="font-weight: 400;"><input type="radio" name="refDisplay" value="off" checked /> Do Not Include</label>
      <label style="font-weight: 400;"><input type="radio" name="refDisplay" value="on" /> Include</label>
      <span style="margin-left: 1rem;"><strong>Comment:</strong></span>
      <label style="font-weight: 400;"><input type="radio" name="commentDisplay" value="off" checked /> Do Not Include</label>
      <label style="font-weight: 400;"><input type="radio" name="commentDisplay" value="on" /> Include</label>
    </div>

    <div id="embeddedSourceControls" class="controls">
      <span>Vista_Barcode_Fields.csv + ZPL Label Builder_ALL_non_IE3_IE's-Vista_Barcode_Comments.json</span>
      <button id="reloadEmbeddedBtn" class="secondary">Reload Embedded</button>
      <small id="embeddedCommitNotice">Last commit: checking...</small>
    </div>

    <div id="externalSourceControls" style="display: none;">
      <div class="controls">
        <label for="jsonFile">JSON File (Shelf Locations):</label>
        <input id="jsonFile" type="file" accept=".json" />
        <span class="location-hint">📁 Location: \Shelf_Loc_2_CSV_JSON folder\shelf_loc_2_JSON.json</span>
      </div>
      <div class="controls">
        <label for="csvFile">CSV File (Product Data):</label>
        <input id="csvFile" type="file" accept=".csv" />
        <span class="location-hint">📁 Location: \Vista_Bulk_Barcode_Label_Field_Extractor folder\Vista_Barcode_Fields.csv</span>
      </div>
      <div class="controls">
        <label for="commentRefFile">REF &amp; Comment File:</label>
        <input id="commentRefFile" type="file" accept=".json" />
        <span class="location-hint">📁 Location: \IP2Zebra\NON-IE3_Commentor_Utility_ONLY\ZPL Label Builder_ALL_non_IE3_IE's-Vista_Barcode_Comments.json</span>
      </div>
      <div class="controls">
        <label for="ieNumbersFile">IE Numbers.txt (Optional):</label>
        <input id="ieNumbersFile" type="file" accept=".txt,text/plain" /> <span class="file-location">📁 <span style="color:#06c; font-size:inherit;">Location: \HTMLToVistaBridge folder\IE Numbers.txt</span></span>
      </div>
    </div>

    <div class="controls">
      <label for="ieSearchInput">IE:</label>
      <div class="ie-picker">
        <input id="ieSearchInput" type="text" autocomplete="off" placeholder="N/A" disabled />
        <div id="ieOptions" class="ie-options"></div>
    <div id="ieSelectPrompt" style="display:none; position:relative; margin:12px 0 10px 30px; padding:12px 16px; max-width:520px; background:#fff200; border:4px solid #e60000; border-radius:10px; color:#000; font-size:15px; line-height:1.35; font-weight:700; box-shadow:0 4px 12px rgba(0,0,0,.28); z-index:20;">
      <div style="position:absolute; left:24px; top:-35px; font-size:42px; line-height:42px; color:#e60000;">⬆</div>
      Select an IE location from the IE dropdown above to display labels.<br>
      Do NOT activate Include REF or Include Comment until AFTER you have selected an IE location.
    </div>
      </div>
      <small id="ieSelectionStatus">N/A — All IE's</small>
    </div>

    <div class="controls">
      <button id="filterBtn" class="secondary" disabled>Filter & Select</button>
      <button id="downloadAllBtn" class="secondary" disabled>Download ALL (.zpl)</button>
      <button id="copyPSBtn" class="secondary" disabled>Copy PowerShell Command</button>
      <button id="exportCSVBtn" class="secondary" disabled>Export to CSV</button>
      <small id="status"></small>
    </div>

    <table id="dataTable">
      <thead>
        <tr>
          <th style="width: 50px;">Row</th>
          <th style="width: 80px;">IMF</th>
          <th style="width: 150px;">Description</th>
          <th style="width: 80px;">PAR Level</th>
          <th style="width: 100px;">Location</th>
          <th style="width: 80px;">IE</th>
          <th style="width: 130px;">Label Preview</th>
          <th style="width: 120px;">Actions</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>

  <div id="filterModal" class="modal">
    <div class="modal-content">
      <div style="font-size: 1.2rem; font-weight: 600; margin-bottom: 1rem;">
        <span class="modal-close" onclick="document.getElementById('filterModal').classList.remove('active')">&times;</span>
        Filter Labels by Location
      </div>
      <div id="filterTree" class="filter-tree"></div>
      <div class="filter-info">
        <strong id="selectedCount">0</strong> labels selected
      </div>
      <div class="filter-actions">
        <button onclick="applyFilterSelection()">Apply Filter</button>
        <button onclick="resetAllCheckboxes()" class="secondary">Reset All</button>
        <button onclick="document.getElementById('filterModal').classList.remove('active')" class="secondary">Cancel</button>
      </div>
    </div>
  </div>

  <script>
    const patterns=["BaBbBb","BbBaBb","BbBbBa","AbAbBc","AbAcBb","AcAbBb","AbBbAc","AbBcAb","AcBbAb","BbAbAc","BbAcAb","BcAbAb","AaBbCb","AbBaCb","AbBbCa","AaCbBb","AbCaBb","AbCbBa","BbCbAa","BbAaCb","BbAbCa","BaCbAb","BbCaAb","CaCaCa","CaAbBb","CbAaBb","CbAbBa","CaBbAb","CbBaAb","CbBbAa","BaBaBc","BaBcBa","BcBaBa","AaAcBc","AcAaBc","AcAcBa","AaBcAc","AcBaAc","AcBcAa","BaAcAc","BcAaAc","BcAcAa","AaBaCc","AaBcCa","AcBaCa","AaCaBc","AaCcBa","AcCaBa","CaCaBa","BaAcCa","BcAaCa","BaCaAc","BaCcAa","BaCaCa","CaAaBc","CaAcBa","CcAaBa","CaBaAc","CaBcAa","CcBaAa","CaDaAa","BbAdAa","DcAaAa","AaAbBd","AaAdBb","AbAaBd","AbAdBa","AdAaBb","AdAbBa","AaBbAd","AaBdAb","AbBaAd","AbBdAa","AdBaAb","AdBbAa","BdAbAa","BbAaAd","DaCaAa","BdAaAb","AcDaAaa","AaAbDb","AbAaDb","AbAbDa","AaDbAb","AbDaAb","AbDbAa","DaAbAb","DbAaAb","DbAbAa","BaBaDa","BaDaBa","DaBaBa","AaAaDc","AaAcDa","AcAaDa","AaDaAc","AaDcAa","DaAaAc","DaAcAa","AaCaDa","AaDaCa","CaAaDa","DaAaCa","BaAdAb","BaAbAd","BaAbCb","BcCaAaB"];

    let allLabels = [];
    let shelfData = [];
    let filteredLabels = [];
    let productData = {};
    let csvRecords = [];
    let commentRefRecords = [];
    let ieDirectory = [];
    let selectedIE = '';

    function tokens(s){let out=[],rx=/[\^~][A-Za-z0-9@\&]{1,2}/g,m,last=0;while((m=rx.exec(s))){if(m.index>last&&out.length)out[out.length-1].arg+=s.slice(last,m.index);out.push({cmd:m[0],arg:''});last=rx.lastIndex}if(last<s.length&&out.length)out[out.length-1].arg+=s.slice(last);return out}
    function number(s,d){let n=Number(s);return s==null||s.trim()===''||!Number.isFinite(n)?d:n}
    function parse(s){const t=tokens(s),warnings=[],labels=[],unsupported=new Set;let state=null,field=null;function fresh(){state={width:0,height:0,origin:[0,0],shift:0,font:{h:30,w:30,face:'0',rot:'N'},barcode:{w:2,ratio:3,h:100},reverse:false,items:[],ci:28};field=null}function commit(){if(!field)return;let raw=field.data||'';if(field.hex){raw=raw.replace(new RegExp(field.hex+'([0-9a-fA-F]{2})','g'),(_,hex)=>String.fromCharCode(parseInt(hex,16)))}state.items.push({...field,data:raw});field=null}for(const {cmd,arg} of t){if(cmd==='^XA'){if(state){commit();labels.push(state)}fresh();continue}if(!state)continue;let a=arg.split(',');switch(cmd){case '^XZ':commit();labels.push(state);state=null;break;case '^PW':state.width=number(arg,0);break;case '^LL':state.height=number(arg,0);break;case '^LH':state.origin=[number(a[0],0),number(a[1],0)];break;case '^LS':state.shift=number(arg,0);break;case '^CI':state.ci=number(arg,28);break;case '^FO':case '^FT':commit();field={x:number(a[0],0),y:number(a[1],0),baseline:cmd==='^FT',font:{...state.font},barcode:null,data:'',block:null,reverse:state.reverse,hex:null};break;case '^A0':case '^AN':case '^AA':case '^AB':case '^AC':case '^AD':case '^AE':case '^AF':case '^AG':case '^AH':case '^AI':case '^AJ':case '^AK':case '^AL':case '^AM':case '^AP':case '^AQ':case '^AR':case '^AS':case '^AT':case '^AU':case '^AV':case '^AW':case '^AX':case '^AY':case '^AZ':{let f={face:cmd.slice(2),rot:a[0]||'N',h:number(a[1],30),w:number(a[2],number(a[1],30))};if(field)field.font=f;else state.font=f;break}case '^CF':state.font={face:a[0]||'0',rot:'N',h:number(a[1],30),w:number(a[2],number(a[1],30))};break;case '^BY':state.barcode={w:number(a[0],2),ratio:number(a[1],3),h:number(a[2],100)};break;case '^BC':if(!field)field={x:0,y:0,baseline:false,font:{...state.font},data:'',block:null,reverse:state.reverse,hex:null};field.barcode={...state.barcode,rot:a[0]||'N',h:number(a[1],state.barcode.h),read:(a[2]||'Y')!=='N',above:(a[3]||'N')==='Y',check:(a[4]||'N')==='Y',mode:a[5]||'N'};break;case '^FB':if(field)field.block={width:number(a[0],0),lines:number(a[1],1),gap:number(a[2],0),align:a[3]||'L',indent:number(a[4],0)};break;case '^FH':if(field)field.hex=(arg.trim()||'_')[0];break;case '^FD':if(!field)field={x:0,y:0,baseline:false,font:{...state.font},data:'',block:null,reverse:state.reverse,hex:null};field.data+=arg;break;case '^FS':commit();break;case '^FR':if(field)field.reverse=true;else state.reverse=true;break;default:break}}if(state){commit();labels.push(state)}return {label:labels[0],warnings}}
    function encode128(raw){let codes=[],subset='B',i=0;function switchTo(s){if(!codes.length)codes.push(s==='C'?105:104);else if(subset!==s)codes.push(s==='C'?99:100);subset=s}switchTo('B');while(i<raw.length){let run=(raw.slice(i).match(/^\d+/)||[''])[0].length;if(subset==='B'&&run>=4){let len=run-(run%2);if(len>=4){switchTo('C');continue}}if(subset==='C'){if(run>=2){codes.push(Number(raw.slice(i,i+2)));i+=2;continue}switchTo('B');continue}let n=raw.charCodeAt(i);if(n>=32&&n<=126)codes.push(n-32);else codes.push(0);i++}if(codes.length===1)throw Error('No barcode data');let checksum=codes[0];for(let j=1;j<codes.length;j++)checksum+=codes[j]*j;codes.push(checksum%103,106);return codes}
    function barcode(ctx,item,x,y){let b=item.barcode;let codes=encode128(item.data),modules=[];for(let code of codes)for(let char of patterns[code])modules.push({bar:char>='A'&&char<='D',width:char.toLowerCase().charCodeAt(0)-96});let bw=Math.max(.5,b.w),height=Math.max(1,b.h),bars=modules.reduce((a,m)=>a+m.width,0)*bw;ctx.save();ctx.translate(x,y);let rot={N:0,R:Math.PI/2,I:Math.PI,B:-Math.PI/2}[b.rot]||0;ctx.rotate(rot);let top=b.read&&b.above?Math.max(18,bw*9):0;ctx.fillStyle='#000';let cursor=0;for(let m of modules){if(m.bar)ctx.fillRect(cursor,top,m.width*bw,height);cursor+=m.width*bw}if(b.read){ctx.font=`${Math.max(14,Math.min(28,bw*9))}px Arial`;ctx.textAlign='center';ctx.textBaseline='top';ctx.fillText(item.data.replace(/>;|>:|>9/g,''),bars/2,b.above?0:top+height+5,bars)}ctx.restore();return {width:bars,height:top+height+(b.read&&!b.above?Math.max(25,bw*12):0)}}
    function drawText(ctx,item,x,y){let f=item.font,h=Math.max(1,f.h),w=Math.max(1,f.w),lines=item.data.replace(/\&/g,'\n').split('\n');ctx.save();ctx.translate(x,y);ctx.rotate(({N:0,R:Math.PI/2,I:Math.PI,B:-Math.PI/2})[f.rot]||0);let scale=w/h;ctx.scale(scale,1);ctx.font=`${h}px Arial`;ctx.textBaseline=item.baseline?'alphabetic':'top';ctx.fillStyle='#000';let step=h+(item.block?.gap||0);if(item.block){let max=item.block.lines||lines.length;lines=lines.slice(0,max)}for(let i=0;i<lines.length;i++){let line=lines[i],offset=i===0?(item.block?.indent||0):0;if(item.block?.width){let bound=item.block.width/scale;ctx.textAlign=item.block.align==='C'?'center':item.block.align==='R'?'right':'left';let ax=item.block.align==='C'?bound/2:item.block.align==='R'?bound:offset;ctx.fillText(line,ax,i*step,bound)}else{ctx.textAlign='left';ctx.fillText(line,0,i*step)}}ctx.restore()}
    function renderLabel(canvas, zpl) {try {let {label}=parse(zpl);if(!label)throw Error('No label found');if(!label.items.length)throw Error('No fields found');let maxX=0,maxY=0;for(let it of label.items){maxX=Math.max(maxX,it.x+(it.barcode?400:Math.max(80,it.data.length*it.font.w*.7)));maxY=Math.max(maxY,it.y+(it.barcode?it.barcode.h+45:it.font.h*2))}let W=Math.round(label.width||Math.max(400,maxX+20)),H=Math.round(label.height||Math.max(200,maxY+20));canvas.width=W;canvas.height=H;const ctx=canvas.getContext('2d');ctx.fillStyle='#fff';ctx.fillRect(0,0,W,H);for(let item of label.items){let x=item.x+label.origin[0]+label.shift,y=item.y+label.origin[1];if(item.barcode)barcode(ctx,item,x,y);else drawText(ctx,item,x,y)}} catch(e) {canvas.width=400;canvas.height=200;const ctx=canvas.getContext('2d');ctx.fillStyle='#fff';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.fillStyle='#f00';ctx.font='12px Arial';ctx.fillText('Render error',5,15);}}

    function downloadText(filename, text) {
      const blob = new Blob([text], {type: 'text/plain'});
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    }

    function zplSafe(value) {
      return (value ?? '').toString().replace(/[\^~]/g, ' ');
    }

    function buildZPL(ie, imf, description, parLevel, location, ref='', comment='') {
      const combined = (ie ?? '').toString() + ' ' + (imf ?? '').toString();
      const includeRef = document.querySelector('input[name="refDisplay"]:checked')?.value === 'on';
      const includeComment = document.querySelector('input[name="commentDisplay"]:checked')?.value === 'on';

      let humanText = combined;
      if (includeRef && ref) humanText += ' REF:' + ref;
      if (includeComment && comment) humanText += ' (' + comment + ')';

      // REF and Comment are human-readable text only.
      // Code 128 barcode data remains exactly the original IE + space + IMF value.
      return '^XA^LH10,40^PON^FO0,0^AR^FD' + zplSafe(description) +
        '^FS^FO0,40^AR^FD' + zplSafe(parLevel) + ' R:10 UoI:EA OD: PARX ' + zplSafe(location) +
        '^FS^FO0,80^AS^BCN,45,N,N,N^FD' + zplSafe(combined) +
        '^FS^FO0,130^AS^FD' + zplSafe(humanText) + '^FS^XZ';
    }

    function getProductInfo(imf) {
      const key = imf.toString();
      return productData[key] || {description: 'UNK', parLevel: 'UNK'};
    }

    function parseCSVLine(line) {
      const result = [];
      let current = '';
      let insideQuotes = false;
      for (let i = 0; i < line.length; i++) {
        const char = line[i];
        const nextChar = line[i + 1];
        if (char === '"') {
          if (insideQuotes && nextChar === '"') {
            current += '"';
            i++;
          } else {
            insideQuotes = !insideQuotes;
          }
        } else if (char === ',' && !insideQuotes) {
          result.push(current);
          current = '';
        } else {
          current += char;
        }
      }
      result.push(current);
      return result;
    }

    function insertRow(data, rowNum) {
      const tr = document.createElement('tr');
      const mk = (text) => {const td = document.createElement('td'); td.textContent = text; return td;};
      const prodInfo = getProductInfo(data.imf);

      tr.appendChild(mk(rowNum));
      tr.appendChild(mk(data.imf));

      const descTd = document.createElement('td');
      if (prodInfo.description === 'UNK') {
        descTd.innerHTML = '<span class="unk">UNK</span>';
      } else {
        descTd.textContent = prodInfo.description;
      }
      tr.appendChild(descTd);

      const parTd = document.createElement('td');
      if (prodInfo.parLevel === 'UNK') {
        parTd.innerHTML = '<span class="unk">UNK</span>';
      } else {
        parTd.textContent = prodInfo.parLevel;
      }
      tr.appendChild(parTd);

      tr.appendChild(mk(data.shelf_loc));
      tr.appendChild(mk(data.ie));

      const tdPreview = document.createElement('td');
      tdPreview.className = 'barcode-cell';
      const canvas = document.createElement('canvas');
      const previewZpl = data.zpl || buildZPL(data.ie, data.imf, prodInfo.description, prodInfo.parLevel, data.shelf_loc, data.ref, data.comment);
      renderLabel(canvas, previewZpl);
      tdPreview.appendChild(canvas);
      tr.appendChild(tdPreview);

      const tdActions = document.createElement('td');
      const actions = document.createElement('div');
      actions.className = 'row-actions';
      const btnCopyPS = document.createElement('button');
      btnCopyPS.textContent = 'Copy PS Cmd';
      btnCopyPS.className = 'secondary';
      btnCopyPS.onclick = async () => {
        const doublePrint = document.getElementById('doublePrintCheckbox').checked;
        let zplContent = data.zpl;
        if (doublePrint) zplContent += data.zpl;
        const printerIP = (document.getElementById('printerIP').value || '10.148.103.100').trim();
        const port = 9100;
        const escapedZpl = zplContent.replace(/"/g, '\\"');
        const psCmd = '$printerIP = "' + printerIP + '"; $port = ' + port + '; $zpl = "' + escapedZpl + '"; $client = New-Object System.Net.Sockets.TcpClient($printerIP, $port); $stream = $client.GetStream(); $bytes = [System.Text.Encoding]::ASCII.GetBytes($zpl); $stream.Write($bytes, 0, $bytes.Length); $stream.Flush(); $stream.Close(); $client.Close(); Write-Host "Sent to printer."';
        await navigator.clipboard.writeText(psCmd);
        const originalText = btnCopyPS.textContent;
        btnCopyPS.textContent = 'Copied!';
        setTimeout(() => {btnCopyPS.textContent = originalText;}, 2000);
        alert('PowerShell command copied!\n\nStep 1: Win+X, I\nStep 2: Ctrl+V, Enter\nStep 3: type exit, Enter');
      };
      actions.appendChild(btnCopyPS);
      tdActions.appendChild(actions);
      tr.appendChild(tdActions);

      document.querySelector('#dataTable tbody').appendChild(tr);
    }

    function renderTable(labels) {
      const tbody = document.querySelector('#dataTable tbody');
      tbody.innerHTML = '';
      labels.forEach((label, idx) => insertRow(label, idx + 1));
    }

    function parseLocation(loc) {
      const panelMatch = loc.match(/^P(\d+)R(\d+)B(\d+)$/i);
      if (panelMatch) {
        return {format: 'panel', panel: 'P' + panelMatch[1], row: 'R' + panelMatch[2], bin: 'B' + panelMatch[3]};
      }
      return null;
    }

    function buildFilterTree() {
      const structure = {};
      getIEFilteredLabels().forEach(label => {
        const ie = (label.ie ?? '').toString().trim() || 'UNKNOWN IE';
        if (!structure[ie]) structure[ie] = { panels: {}, unknown: [] };

        const parsed = parseLocation((label.shelf_loc ?? '').toString().trim());
        if (!parsed) {
          structure[ie].unknown.push(label);
          return;
        }

        if (!structure[ie].panels[parsed.panel]) structure[ie].panels[parsed.panel] = {};
        if (!structure[ie].panels[parsed.panel][parsed.row]) structure[ie].panels[parsed.panel][parsed.row] = {};
        if (!structure[ie].panels[parsed.panel][parsed.row][parsed.bin]) structure[ie].panels[parsed.panel][parsed.row][parsed.bin] = [];
        structure[ie].panels[parsed.panel][parsed.row][parsed.bin].push(label);
      });
      return structure;
    }

    function renderFilterUI() {
      const structure = buildFilterTree();
      const tree = document.getElementById('filterTree');
      tree.innerHTML = '';
      if (allLabels.length === 0) return;

      Object.keys(structure).sort((a, b) => a.localeCompare(b, undefined, {numeric:true})).forEach(ie => {
        const ieData = structure[ie];
        const ieDiv = document.createElement('div');
        ieDiv.className = 'filter-group';

        const ieHeader = document.createElement('div');
        ieHeader.className = 'section-header';

        const toggleIcon = document.createElement('span');
        toggleIcon.className = 'toggle-icon';
        toggleIcon.textContent = '▶';

        const ieCheck = document.createElement('input');
        ieCheck.type = 'checkbox';
        ieCheck.dataset.ie = ie;
        ieCheck.dataset.scope = 'ie';

        const ieLabel = document.createElement('label');
        ieLabel.style.display = 'inline';
        ieLabel.style.marginLeft = '0.5rem';
        ieLabel.appendChild(document.createTextNode('IE ' + ie + ' — Entire IE'));

        const ieContents = document.createElement('div');
        ieContents.className = 'rows-container';
        ieContents.style.display = 'none';

        ieHeader.appendChild(toggleIcon);
        ieHeader.appendChild(ieCheck);
        ieHeader.appendChild(ieLabel);

        ieHeader.addEventListener('click', (e) => {
          if (e.target !== ieCheck) {
            const isVisible = ieContents.style.display !== 'none';
            ieContents.style.display = isVisible ? 'none' : 'block';
            toggleIcon.textContent = isVisible ? '▶' : '▼';
          }
        });

        ieCheck.addEventListener('change', updateSelectedCount);

        if (ieData.unknown.length > 0) {
          const unknownItem = document.createElement('div');
          unknownItem.style.margin = '0.4rem 0 0.6rem 1.5rem';

          const unknownCheck = document.createElement('input');
          unknownCheck.type = 'checkbox';
          unknownCheck.dataset.ie = ie;
          unknownCheck.dataset.scope = 'unknown';

          const unknownLabel = document.createElement('label');
          unknownLabel.appendChild(unknownCheck);
          unknownLabel.appendChild(document.createTextNode(
            ' Unknown Shelf Location (' + ieData.unknown.length + ' item' +
            (ieData.unknown.length === 1 ? '' : 's') + ')'
          ));
          unknownItem.appendChild(unknownLabel);
          ieContents.appendChild(unknownItem);
        }

        Object.keys(ieData.panels).sort((a, b) => a.localeCompare(b, undefined, {numeric:true})).forEach(panel => {
          const panelDiv = document.createElement('div');
          panelDiv.className = 'filter-group';

          const panelHeader = document.createElement('div');
          panelHeader.className = 'section-header';

          const panelToggle = document.createElement('span');
          panelToggle.className = 'toggle-icon';
          panelToggle.textContent = '▶';

          const panelCheck = document.createElement('input');
          panelCheck.type = 'checkbox';
          panelCheck.dataset.ie = ie;
          panelCheck.dataset.panel = panel;
          panelCheck.dataset.scope = 'panel';

          const panelLabel = document.createElement('label');
          panelLabel.style.display = 'inline';
          panelLabel.style.marginLeft = '0.5rem';
          panelLabel.appendChild(document.createTextNode('Panel ' + panel));

          const rowsContainer = document.createElement('div');
          rowsContainer.className = 'rows-container';
          rowsContainer.style.display = 'none';

          panelHeader.appendChild(panelToggle);
          panelHeader.appendChild(panelCheck);
          panelHeader.appendChild(panelLabel);

          panelHeader.addEventListener('click', (e) => {
            if (e.target !== panelCheck) {
              const isVisible = rowsContainer.style.display !== 'none';
              rowsContainer.style.display = isVisible ? 'none' : 'block';
              panelToggle.textContent = isVisible ? '▶' : '▼';
            }
          });

          panelCheck.addEventListener('change', updateSelectedCount);

          Object.keys(ieData.panels[panel]).sort((a, b) => parseInt(a.replace(/\D/g,'')) - parseInt(b.replace(/\D/g,''))).forEach(row => {
            const rowDiv = document.createElement('div');
            rowDiv.className = 'row-item';

            const rowCheck = document.createElement('input');
            rowCheck.type = 'checkbox';
            rowCheck.dataset.ie = ie;
            rowCheck.dataset.panel = panel;
            rowCheck.dataset.row = row;
            rowCheck.dataset.scope = 'row';
            rowCheck.addEventListener('change', updateSelectedCount);

            const rowLabel = document.createElement('label');
            rowLabel.appendChild(rowCheck);
            rowLabel.appendChild(document.createTextNode('Row ' + row));
            rowDiv.appendChild(rowLabel);

            const binsDiv = document.createElement('div');
            binsDiv.className = 'bins-container';

            Object.keys(ieData.panels[panel][row]).sort((a, b) => a.localeCompare(b, undefined, {numeric:true})).forEach(bin => {
              const binItem = document.createElement('div');

              const binCheck = document.createElement('input');
              binCheck.type = 'checkbox';
              binCheck.dataset.ie = ie;
              binCheck.dataset.panel = panel;
              binCheck.dataset.row = row;
              binCheck.dataset.bin = bin;
              binCheck.dataset.scope = 'bin';
              binCheck.addEventListener('change', updateSelectedCount);

              const binLabel = document.createElement('label');
              binLabel.appendChild(binCheck);
              binLabel.appendChild(document.createTextNode('Bin ' + bin));
              binItem.appendChild(binLabel);
              binsDiv.appendChild(binItem);
            });

            rowDiv.appendChild(binsDiv);
            rowsContainer.appendChild(rowDiv);
          });

          panelDiv.appendChild(panelHeader);
          panelDiv.appendChild(rowsContainer);
          ieContents.appendChild(panelDiv);
        });

        ieDiv.appendChild(ieHeader);
        ieDiv.appendChild(ieContents);
        tree.appendChild(ieDiv);
      });
    }

    function updateSelectedCount() {
      const checked = document.querySelectorAll('#filterTree input[type="checkbox"]:checked').length;
      document.getElementById('selectedCount').textContent = checked;
    }

    function resetAllCheckboxes() {
      document.querySelectorAll('#filterTree input[type="checkbox"]').forEach(cb => cb.checked = false);
      updateSelectedCount();
    }

    function applyFilterSelection() {
      const checkedBoxes = document.querySelectorAll('#filterTree input[type="checkbox"]:checked');
      if (checkedBoxes.length === 0) {
        filteredLabels = [];
        document.getElementById('filterModal').classList.remove('active');
        const baseLabels = getIEFilteredLabels();
        renderTable(baseLabels);
        document.getElementById('status').textContent = selectedIE
          ? 'Filter reset. Showing ' + baseLabels.length + ' labels for IE ' + selectedIE + '.'
          : 'Filter reset. Showing all ' + baseLabels.length + ' labels.';
        return;
      }

      const selected = new Set();

      checkedBoxes.forEach(box => {
        const ie = box.dataset.ie;
        const scope = box.dataset.scope;
        const panel = box.dataset.panel;
        const row = box.dataset.row;
        const bin = box.dataset.bin;

        const baseLabels = getIEFilteredLabels();
        baseLabels.forEach((label, idx) => {
          const labelIE = (label.ie ?? '').toString().trim() || 'UNKNOWN IE';
          if (labelIE !== ie) return;

          const parsed = parseLocation((label.shelf_loc ?? '').toString().trim());

          if (scope === 'ie') {
            selected.add(idx);
            return;
          }

          if (scope === 'unknown') {
            if (!parsed) selected.add(idx);
            return;
          }

          if (!parsed) return;
          if (scope === 'panel' && parsed.panel === panel) selected.add(idx);
          if (scope === 'row' && parsed.panel === panel && parsed.row === row) selected.add(idx);
          if (scope === 'bin' && parsed.panel === panel && parsed.row === row && parsed.bin === bin) selected.add(idx);
        });
      });

      const baseLabels = getIEFilteredLabels();
      filteredLabels = Array.from(selected).sort((a, b) => a - b).map(idx => baseLabels[idx]);
      document.getElementById('filterModal').classList.remove('active');
      renderTable(filteredLabels);
      document.getElementById('status').textContent = 'Filtered to ' + filteredLabels.length + ' labels.';
    }

    function exportLabelsToCSV(labels) {
      const csvRows = [];
      csvRows.push('"Row","IMF","Description","PAR Level","Location","IE","ZPL_Command"');
      labels.forEach((label, idx) => {
        const prodInfo = getProductInfo(label.imf);
        const desc = prodInfo.description === 'UNK' ? 'UNK' : prodInfo.description;
        const par = prodInfo.parLevel === 'UNK' ? 'UNK' : prodInfo.parLevel;
        const row = [idx + 1, label.imf, desc, par, label.shelf_loc, label.ie, label.zpl];
        const csvRow = row.map(cell => '"' + (cell || '').toString().replace(/"/g, '""') + '"').join(',');
        csvRows.push(csvRow);
      });
      downloadText('ZPL_Label_Builder_ALL_non_IE3_IEs_v9b_labels_export.csv', csvRows.join('\n'));
    }

    const EMBEDDED_BASE_URL = 'https://deweyduck6116.github.io/Inventory/';
    const EMBEDDED_CSV_URL = EMBEDDED_BASE_URL + 'Vista_Barcode_Fields.csv';
    const EMBEDDED_SHELF_JSON_URL = EMBEDDED_BASE_URL + 'shelf_loc_2_JSON.JSON';
    const EMBEDDED_IE_NUMBERS_URL = EMBEDDED_BASE_URL + 'IE%20Numbers.txt';
    const EMBEDDED_JSON_URL = EMBEDDED_BASE_URL + "ZPL%20Label%20Builder_ALL_non_IE3_IE%27s-Vista_Barcode_Comments.json";
    const GITHUB_COMMITS_API = 'https://api.github.com/repos/deweyduck6116/Inventory/commits?per_page=1&path=';

    function parseIENumbersText(text) {
      const parsed = [];
      text.split(/\r?\n/).forEach(line => {
        const m = line.match(/^\s*(\d+)\s+(.+?)\s*$/);
        if (!m) return;
        const ie = m[1].trim();
        const fullName = m[2].trim();
        const displayName = fullName.replace(/^644-/i, '');
        parsed.push({ie, fullName, displayName});
      });
      if (!parsed.length) throw new Error('No IE entries found in IE Numbers.txt');
      ieDirectory = parsed.sort((a, b) => Number(a.ie) - Number(b.ie));
      selectedIE = '';
      const input = document.getElementById('ieSearchInput');
      input.disabled = false;
      input.value = '';
      document.getElementById('ieSelectionStatus').textContent = "N/A — All IE's";
      renderIEOptions('');
    }

    function disableIEFeature() {
      ieDirectory = [];
      selectedIE = '';
      filteredLabels = [];
      const input = document.getElementById('ieSearchInput');
      if (input) {
        input.value = '';
        input.disabled = true;
      }
      const options = document.getElementById('ieOptions');
      if (options) {
        options.innerHTML = '';
        options.classList.remove('active');
      }
      const status = document.getElementById('ieSelectionStatus');
      if (status) status.textContent = "N/A — All IE's";
    }

    function getIEFilteredLabels() {
      if (!selectedIE) return allLabels;
      return allLabels.filter(label => String(label.ie ?? '').trim().replace(/^IE[\s-]*/i, '').trim() === selectedIE);
    }

    function renderCurrentIEScope() {
      filteredLabels = [];
      const labels = getIEFilteredLabels();
      const prompt = document.getElementById('ieSelectPrompt');

      if (selectedIE) {
        if (prompt) prompt.style.display = 'none';
        renderTable(labels);
      } else {
        // TEMPORARY TEST ONLY: render the complete label list when N/A — All IE's is selected.
        // Do not treat this behavior as permanent unless the developer explicitly approves it.
        renderTable(labels);
        if (prompt) prompt.style.display = 'block';
      }

      const entry = ieDirectory.find(x => x.ie === selectedIE);
      document.getElementById('ieSelectionStatus').textContent = selectedIE
        ? selectedIE + ' — ' + (entry?.displayName || 'Selected IE')
        : "N/A — All IE's";
      document.getElementById('status').textContent = selectedIE
        ? 'Showing ' + labels.length + ' labels for IE ' + selectedIE + '.'
        : 'Labels loaded. Select an IE location above to display results.';
    }

    function chooseIE(entry) {
      const input = document.getElementById('ieSearchInput');
      if (!entry) {
        selectedIE = '';
        input.value = '';
      } else {
        selectedIE = entry.ie;
        input.value = entry.ie + ' — ' + entry.displayName;
      }
      document.getElementById('ieOptions').classList.remove('active');
      renderCurrentIEScope();
    }

    function renderIEOptions(query) {
      const box = document.getElementById('ieOptions');
      if (!box || !ieDirectory.length) return;
      const q = (query || '').trim().toLowerCase().replace(/^644-/, '');
      box.innerHTML = '';

      const na = document.createElement('div');
      na.className = 'ie-option';
      na.textContent = "N/A — All IE's";
      na.onclick = () => chooseIE(null);
      box.appendChild(na);

      ieDirectory.filter(entry => {
        if (!q || q === 'n/a' || q === 'na') return true;
        return entry.ie.toLowerCase().includes(q) ||
               entry.displayName.toLowerCase().includes(q) ||
               entry.fullName.toLowerCase().includes(q);
      }).forEach(entry => {
        const div = document.createElement('div');
        div.className = 'ie-option';
        div.textContent = entry.ie + ' — ' + entry.displayName;
        div.onclick = () => chooseIE(entry);
        box.appendChild(div);
      });
    }

    function setupIESearch() {
      const input = document.getElementById('ieSearchInput');
      const box = document.getElementById('ieOptions');

      input.addEventListener('focus', () => {
        if (input.disabled || !ieDirectory.length) return;
        renderIEOptions(selectedIE ? '' : input.value);
        box.classList.add('active');
      });

      input.addEventListener('input', () => {
        if (!ieDirectory.length) return;
        renderIEOptions(input.value);
        box.classList.add('active');
      });

      input.addEventListener('keydown', e => {
        const opts = Array.from(box.querySelectorAll('.ie-option'));
        if (!opts.length) return;
        let idx = opts.findIndex(x => x.classList.contains('active'));
        if (e.key === 'ArrowDown') {
          e.preventDefault();
          idx = Math.min(idx + 1, opts.length - 1);
        } else if (e.key === 'ArrowUp') {
          e.preventDefault();
          idx = Math.max(idx - 1, 0);
        } else if (e.key === 'Enter') {
          e.preventDefault();
          if (idx >= 0) opts[idx].click();
          else if (opts.length === 2 && input.value.trim()) opts[1].click();
          return;
        } else if (e.key === 'Escape') {
          box.classList.remove('active');
          return;
        } else return;
        opts.forEach(x => x.classList.remove('active'));
        opts[idx]?.classList.add('active');
        opts[idx]?.scrollIntoView({block:'nearest'});
      });

      document.addEventListener('click', e => {
        if (!e.target.closest('.ie-picker')) box.classList.remove('active');
      });
    }

    function formatCommitAge(dateText) {
      const then = new Date(dateText);
      const seconds = Math.max(0, Math.floor((Date.now() - then.getTime()) / 1000));
      const days = Math.floor(seconds / 86400);
      const hours = Math.floor((seconds % 86400) / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      if (days > 0) return days + ' day' + (days === 1 ? '' : 's') + ', ' + hours + ' hour' + (hours === 1 ? '' : 's') + ' ago';
      if (hours > 0) return hours + ' hour' + (hours === 1 ? '' : 's') + ', ' + minutes + ' minute' + (minutes === 1 ? '' : 's') + ' ago';
      return minutes + ' minute' + (minutes === 1 ? '' : 's') + ' ago';
    }

    async function getLastCommit(path) {
      const response = await fetch(GITHUB_COMMITS_API + encodeURIComponent(path), {cache: 'no-store'});
      if (!response.ok) throw new Error('HTTP ' + response.status);
      const commits = await response.json();
      if (!commits.length) throw new Error('No commit found');
      const dateText = commits[0]?.commit?.committer?.date || commits[0]?.commit?.author?.date;
      if (!dateText) throw new Error('Commit date unavailable');
      const date = new Date(dateText);
      return date.toLocaleString() + ' (' + formatCommitAge(dateText) + ')';
    }

    async function updateEmbeddedCommitNotice() {
      const notice = document.getElementById('embeddedCommitNotice');
      if (!notice) return;
      try {
        const [csvCommit, jsonCommit] = await Promise.all([
          getLastCommit('Vista_Barcode_Fields.csv'),
          getLastCommit("ZPL Label Builder_ALL_non_IE3_IE's-Vista_Barcode_Comments.json")
        ]);

        let ieCommit = 'unavailable';
        try {
          ieCommit = await getLastCommit('IE Numbers.txt');
        } catch (ieCommitErr) {
          ieCommit = 'unavailable (' + ieCommitErr.message + ')';
        }

        notice.textContent = 'Last commit — Vista_Barcode_Fields.csv: ' + csvCommit +
          ' | combined label JSON: ' + jsonCommit +
          ' | IE Numbers.txt: ' + ieCommit;
      } catch (err) {
        notice.textContent = 'Last commit: unable to retrieve commit dates (' + err.message + ').';
      }
    }

    function resetData() {
      allLabels = [];
      filteredLabels = [];
      productData = {};
      csvRecords = [];
      commentRefRecords = [];
      disableIEFeature();
      document.querySelector('#dataTable tbody').innerHTML = '';
      document.getElementById('downloadAllBtn').disabled = true;
      document.getElementById('exportCSVBtn').disabled = true;
      document.getElementById('filterBtn').disabled = true;
      document.getElementById('copyPSBtn').disabled = true;
    }

    function loadJSONText(text) {
      const jsonData = JSON.parse(text);
      if (!Array.isArray(jsonData)) {
        throw new Error('Combined JSON must be an array containing IE, shelf_loc, IMF, Comment, and REF data.');
      }
      commentRefRecords = jsonData.filter(record => record && record.imf !== undefined && record.imf !== null).map(record => ({
        ie: record.ie ?? '',
        shelf_loc: record.shelf_loc ?? '',
        imf: record.imf,
        comment: record.comment ?? '',
        ref: record.ref ?? ''
      }));
      // External mode uses the combined JSON as its complete label/shelf source.
      // Embedded mode replaces shelfData with authoritative shelf_loc_2_JSON.JSON after this call,
      // while commentRefRecords remains the independent Comment/REF metadata source.
      shelfData = commentRefRecords.slice();
    }

    function loadCSVText(text) {
      const lines = text.split(/\r?\n/);
      productData = {};
      csvRecords = [];
      for (let i = 1; i < lines.length; i++) {
        if (!lines[i].trim()) continue;
        const parts = parseCSVLine(lines[i]);
        if (parts.length >= 4) {
          const imf = parts[0].trim();
          if (!imf) continue;
          const description = parts[1].trim() || 'UNK';
          const ie = parts.length >= 3 ? parts[2].trim() : '';
          const parLevel = parts[3].trim() || 'UNK';
          const comment = parts.length >= 5 ? parts[4].trim() : '';
          const ref = parts.length >= 6 ? parts[5].trim() : '';
          csvRecords.push({imf, description, ie, parLevel, comment, ref});
          productData[imf] = {description, parLevel, comment, ref, ie};
        }
      }
    }

    function completeLabels() {
      const normIE = value => String(value ?? '').trim().replace(/^IE[\s-]*/i, '').trim();
      const normIMF = value => String(value ?? '').trim();

      allLabels = [];
      filteredLabels = [];

      // IMPORTANT: The non-IE3 printer list is driven by the complete shelf/IE records,
      // not by the CSV. This preserves every IE selection and prevents Comment/REF
      // enrichment from shrinking or otherwise changing the printer's IE list.
      const exactMeta = new Map();
      const metaByIMF = new Map();

      commentRefRecords.forEach(r => {
        const imf = normIMF(r.imf);
        const ie = normIE(r.ie);
        if (!imf) return;
        const comment = String(r.comment ?? '').trim();
        const ref = String(r.ref ?? '').trim();
        if (comment || ref) {
          const key = imf + '\u0000' + ie;
          const currentExact = exactMeta.get(key) || {comment:'', ref:''};
          if (!currentExact.comment && comment) currentExact.comment = comment;
          if (!currentExact.ref && ref) currentExact.ref = ref;
          exactMeta.set(key, currentExact);

          const currentIMF = metaByIMF.get(imf) || {comment:'', ref:''};
          if (!currentIMF.comment && comment) currentIMF.comment = comment;
          if (!currentIMF.ref && ref) currentIMF.ref = ref;
          metaByIMF.set(imf, currentIMF);
        }
      });

      shelfData.forEach(j => {
        const imf = normIMF(j.imf);
        if (!imf) return;
        const ie = normIE(j.ie);
        const csv = productData[imf] || {description:'UNK', parLevel:'UNK', comment:'', ref:'', ie:''};
        const exact = exactMeta.get(imf + '\u0000' + ie) || {};
        const fallback = metaByIMF.get(imf) || {};
        const comment = String(exact.comment ?? '').trim() || String(fallback.comment ?? '').trim() || String(csv.comment ?? '').trim() || '';
        const ref = String(exact.ref ?? '').trim() || String(fallback.ref ?? '').trim() || String(csv.ref ?? '').trim() || '';
        const labelIE = String(j.ie ?? '').trim() || String(csv.ie ?? '').trim();
        const location = String(j.shelf_loc ?? '').trim();

        allLabels.push({
          ie: labelIE,
          shelf_loc: location,
          imf,
          comment,
          ref,
          zpl: buildZPL(labelIE, imf, csv.description || 'UNK', csv.parLevel || 'UNK', location, ref, comment)
        });
      });

      allLabels.sort((a, b) => {
        const ieCmp = normIE(a.ie).localeCompare(normIE(b.ie), undefined, {numeric:true, sensitivity:'base'});
        if (ieCmp) return ieCmp;
        return String(a.imf ?? '').localeCompare(String(b.imf ?? ''), undefined, {numeric:true, sensitivity:'base'});
      });

      renderCurrentIEScope();

      const enabled = allLabels.length > 0;
      document.getElementById('downloadAllBtn').disabled = !enabled;
      document.getElementById('exportCSVBtn').disabled = !enabled;
      document.getElementById('filterBtn').disabled = !enabled;
      document.getElementById('copyPSBtn').disabled = !enabled;
    }

    async function loadEmbeddedSources() {
      resetData();
      document.getElementById('status').textContent = 'Loading embedded data sources...';
      try {
        const [shelfResponse, jsonResponse, csvResponse] = await Promise.all([
          fetch(EMBEDDED_SHELF_JSON_URL, {cache: 'no-store'}),
          fetch(EMBEDDED_JSON_URL, {cache: 'no-store'}),
          fetch(EMBEDDED_CSV_URL, {cache: 'no-store'})
        ]);
        if (!shelfResponse.ok) throw new Error('Shelf-location JSON HTTP ' + shelfResponse.status);
        if (!jsonResponse.ok) throw new Error('Comment/REF JSON HTTP ' + jsonResponse.status);
        if (!csvResponse.ok) throw new Error('CSV HTTP ' + csvResponse.status);

        const [shelfText, jsonText, csvText] = await Promise.all([
          shelfResponse.text(), jsonResponse.text(), csvResponse.text()
        ]);

        // Keep the two responsibilities separate: the combined JSON supplies Comment/REF,
        // while shelf_loc_2_JSON.JSON remains authoritative for the complete IE/shelf list.
        loadJSONText(jsonText);

        const shelfJson = JSON.parse(shelfText);
        if (!Array.isArray(shelfJson)) throw new Error('Shelf-location JSON must be an array.');
        shelfData = shelfJson.filter(r => r && r.imf !== undefined && r.imf !== null).map(r => ({
          ie: r.ie ?? '',
          shelf_loc: r.shelf_loc ?? '',
          imf: r.imf
        }));

        loadCSVText(csvText);
        completeLabels();

        let ieMessage = '';
        try {
          const ieResponse = await fetch(EMBEDDED_IE_NUMBERS_URL, {cache: 'no-store'});
          if (!ieResponse.ok) throw new Error('HTTP ' + ieResponse.status);
          parseIENumbersText(await ieResponse.text());
          ieMessage = ' IE selector loaded.';
        } catch (ieErr) {
          disableIEFeature();
          ieMessage = ' IE selector unavailable; ignored.';
        }

        document.getElementById('status').textContent =
          'Embedded sources loaded: ' + shelfData.length + ' shelf-location records, ' +
          Object.keys(productData).length + ' products. Labels complete.' + ieMessage;
      } catch (err) {
        resetData();
        document.getElementById('status').textContent =
          'Embedded source load failed: ' + err.message + '. Switch to External to select local files.';
      }
    }

    async function loadExternalSources() {
      const shelfFile = document.getElementById('jsonFile').files?.[0];
      const csvFile = document.getElementById('csvFile').files?.[0];
      const commentRefFile = document.getElementById('commentRefFile').files?.[0];
      const ieNumbersFile = document.getElementById('ieNumbersFile').files?.[0];

      // DEVELOPER REMINDER — DO NOT MERGE THESE INPUT RESPONSIBILITIES:
      // shelf_loc_2_JSON.JSON controls the complete non-IE3 IE/shelf-location list.
      // The REF & Comment JSON enriches those records by IMF (and exact IMF+IE when present).
      // Vista_Barcode_Fields.csv supplies product description/PAR data.
      // REF/Comment data must NEVER determine which IE/shelf records exist.
      if (!shelfFile || !csvFile || !commentRefFile) {
        resetData();
        document.getElementById('status').textContent =
          'External source selected. Select Shelf Locations JSON, Product Data CSV, and REF & Comment JSON.';
        return;
      }

      resetData();
      document.getElementById('status').textContent = 'Loading external files...';
      try {
        const [shelfText, csvText, commentRefText] = await Promise.all([
          shelfFile.text(), csvFile.text(), commentRefFile.text()
        ]);

        // Load Comment/REF metadata independently. loadJSONText temporarily fills shelfData,
        // so immediately replace shelfData with the authoritative shelf-location file below.
        loadJSONText(commentRefText);

        const shelfJson = JSON.parse(shelfText);
        if (!Array.isArray(shelfJson)) throw new Error('Shelf-location JSON must be an array.');
        shelfData = shelfJson.filter(r => r && r.imf !== undefined && r.imf !== null).map(r => ({
          ie: r.ie ?? '',
          shelf_loc: r.shelf_loc ?? '',
          imf: r.imf
        }));

        loadCSVText(csvText);
        completeLabels();

        let ieMessage = '';
        if (ieNumbersFile) {
          try {
            parseIENumbersText(await ieNumbersFile.text());
            ieMessage = ' IE selector loaded.';
          } catch (ieErr) {
            disableIEFeature();
            ieMessage = ' IE selector file invalid; ignored.';
          }
        } else {
          disableIEFeature();
          ieMessage = ' IE selector not supplied; ignored.';
        }

        document.getElementById('status').textContent =
          'External files loaded: ' + shelfData.length + ' shelf records, ' +
          Object.keys(productData).length + ' products, REF/Comments loaded. Labels complete.' + ieMessage;
      } catch (err) {
        resetData();
        document.getElementById('status').textContent = 'Error loading external files: ' + err.message;
      }
    }

    function updateDataSourceControls() {
      const embedded = document.getElementById('sourceEmbedded').checked;
      document.getElementById('embeddedSourceControls').style.display = embedded ? 'flex' : 'none';
      document.getElementById('externalSourceControls').style.display = embedded ? 'none' : 'block';
      if (embedded) loadEmbeddedSources();
      else loadExternalSources();
    }

    document.getElementById('sourceEmbedded').addEventListener('change', updateDataSourceControls);
    document.getElementById('sourceExternal').addEventListener('change', updateDataSourceControls);
    document.getElementById('reloadEmbeddedBtn').addEventListener('click', loadEmbeddedSources);
    document.getElementById('jsonFile').addEventListener('change', loadExternalSources);
    document.getElementById('csvFile').addEventListener('change', loadExternalSources);
    document.getElementById('commentRefFile').addEventListener('change', loadExternalSources);
    document.getElementById('ieNumbersFile').addEventListener('change', loadExternalSources);
    document.querySelectorAll('input[name="refDisplay"], input[name="commentDisplay"]').forEach(control => {
      control.addEventListener('change', () => {
        if (allLabels.length > 0) {
          // TEMPORARY FULL-LIST TEST: discard every rendered row before rebuilding.
          // Do not attempt to update the existing ALL-IE table in place when REF/Comment changes.
          document.querySelector('#dataTable tbody').innerHTML = '';
          filteredLabels = [];
          completeLabels();
        }
      });
    });

    document.getElementById('filterBtn').addEventListener('click', () => {
      if (allLabels.length === 0) {alert('Please load JSON file first'); return;}
      renderFilterUI();
      document.getElementById('filterModal').classList.add('active');
    });

    document.getElementById('downloadAllBtn').addEventListener('click', () => {
      const toDownload = filteredLabels.length > 0 ? filteredLabels : getIEFilteredLabels();
      const doublePrint = document.getElementById('doublePrintCheckbox').checked;
      let zplContent = '';
      toDownload.forEach(label => {
        zplContent += label.zpl;
        if (doublePrint) zplContent += label.zpl;
      });
      downloadText('ZPL_Label_Builder_ALL_non_IE3_IEs_v9b_all_labels.zpl', zplContent);
    });

    document.getElementById('copyPSBtn').addEventListener('click', () => {
      const toDownload = filteredLabels.length > 0 ? filteredLabels : getIEFilteredLabels();
      const doublePrint = document.getElementById('doublePrintCheckbox').checked;
      let zplContent = '';
      toDownload.forEach(label => {
        zplContent += label.zpl;
        if (doublePrint) zplContent += label.zpl;
      });
      const printerIP = (document.getElementById('printerIP').value || '10.148.103.100').trim();
      const port = 9100;
      const escapedZpl = zplContent.replace(/"/g, '\\"');
      const psCmd = '$printerIP = "' + printerIP + '"; $port = ' + port + '; $zpl = "' + escapedZpl + '"; $client = New-Object System.Net.Sockets.TcpClient($printerIP, $port); $stream = $client.GetStream(); $bytes = [System.Text.Encoding]::ASCII.GetBytes($zpl); $stream.Write($bytes, 0, $bytes.Length); $stream.Flush(); $stream.Close(); $client.Close(); Write-Host "Sent to printer."';
      navigator.clipboard.writeText(psCmd).then(() => {
        const btn = document.getElementById('copyPSBtn');
        const originalText = btn.textContent;
        btn.textContent = 'Copied!';
        setTimeout(() => {btn.textContent = originalText;}, 2000);
        alert('PowerShell command copied!\n\nWin+X, I → Ctrl+V, Enter → type exit, Enter');
      }).catch(err => {alert('Failed to copy: ' + err);});
    });

    document.getElementById('exportCSVBtn').addEventListener('click', () => {
      const toExport = filteredLabels.length > 0 ? filteredLabels : getIEFilteredLabels();
      if (toExport.length > 0) exportLabelsToCSV(toExport);
    });

    window.addEventListener('DOMContentLoaded', () => {
      setupIESearch();
      updateDataSourceControls();
      updateEmbeddedCommitNotice();
    });
  </script>
</body>
</html>